package com.dsx.test.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.Verification;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.util.CollectionUtils;

import java.util.Date;
import java.util.Map;

/**
 * @author : tianwenqing
 * @version : 1.0
 * @date : 2020-11-16 17:43
 * @description : JWT 相关工具类
 **/
@Slf4j
public class JwtUtil {

    /**
     * 从token或者属性值
     *
     * @param token
     * @param name
     * @return
     */
    public static String getValueByName(String token, String name) {
        try {
            DecodedJWT decode = JWT.decode(token);
            return decode.getClaims().get(name).asString();
        } catch (JWTDecodeException e) {
            log.error("getValueByName ex", e);
        }
        return null;
    }

    /**
     * 生成token
     *
     * @param claims
     * @param secret
     * @param tokenExpireTime
     * @return
     */
    public static String getToken(Map<String, String> claims, String secret, long tokenExpireTime) {
        try {
            Date date = new Date(System.currentTimeMillis() + (tokenExpireTime * 60 * 1000));
            JWTCreator.Builder jwtBuilder = JWT.create().withExpiresAt(date);
            if (!CollectionUtils.isEmpty(claims)) {
                claims.forEach(jwtBuilder::withClaim);
            }
            Algorithm algorithm = Algorithm.HMAC256(secret);
            return jwtBuilder.sign(algorithm);
        } catch (Exception e) {
            log.error("getToken ex", e);
        }
        return null;
    }


    public static Boolean verify(Map<String, String> claims, String token, String secret) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(secret);
            Verification verifier = JWT.require(algorithm);
            if (!CollectionUtils.isEmpty(claims)) {
                claims.forEach(verifier::withClaim);
            }
            verifier.build().verify(token);
            return true;
        } catch (Exception e) {
            log.error("verify ex", e);
        }
        return false;
    }


}
